<template>
    <div id="app">
        <router-view/>
    </div>
</template>

<script>
    import wx from "weixin-js-sdk"
    import {basePrefix, getCookie, getStorageObj} from "./js/utils";
    import {mapMutations, mapState} from "vuex";
    import {TenonWebsocket} from "./js/websocket";
    import qs from 'qs';
    import { Dialog } from 'vant';

    export default {
        name: 'App',
        components: {
            Dialog
        },
        created() {
            //外部浏览器跳过
            let viewer = window.navigator.userAgent.toLowerCase();
            if(viewer.match(/MicroMessenger/i) == 'micromessenger'){
                //微信浏览器
                let jsApiTicket = JSON.parse(Base64.decode(getCookie("jsapiTicket")))
                wx.config({
                    debug: false,
                    beta: true,
                    appId: jsApiTicket.AppId,
                    timestamp: jsApiTicket.Timestamp,
                    nonceStr: jsApiTicket.NonceStr,
                    signature: jsApiTicket.Signature,
                    jsApiList: [
                        'checkJsApi',
                        'getNetworkType',
                        'scanQRCode',
                        'closeWindow',
                        'configWXDeviceWiFi'
                    ]
                })
                //1、设置用户id
                this.loadUserId(jsApiTicket.AppId)
                console.log("userId = ",this.userId)
                //2、设置用户是否已经关注
                this.loadSubscribe()
                //3、url添加调试代码
                this.debug()

                //判断是否关注亚太天能公众号
                this.afterLoadSubscribe()
            }
        },
        computed: {
            ...mapState(["userId","subscribe"])
        },
        methods: {
            ...mapMutations(["setJsapiTicket", "setUserId","setSubscribe"]),
            loadUserId(appId) {
                let userId = this.userId

                if (userId) {
                    console.log("userId = ",userId)
                    return
                }

                userId = getCookie("userId")
                if (userId) {
                    this.setUserId(userId)
                    console.log("userId = ",userId)
                    return
                }
                console.log("重定向")
                const baseUrl = window.location.href.split("#")[0];
                //重定向服务器
                const redirectUrl = encodeURIComponent(baseUrl);
                const dst = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
                window.location.href = dst
            },
            loadSubscribe() {
                let subscribe = this.subscribe
                if (subscribe) {
                    console.log("subscribe = ",subscribe)
                    return
                }
                subscribe = getCookie("subStatus")
                if (subscribe) {
                    this.setSubscribe(subscribe)
                    console.log("subscribe = ",subscribe)
                    return
                }
            },
            onGeneralClick: function (link, queryParams) {
                this.$router.push({
                    path: link,
                    query: queryParams
                });//其中login是你定义的一个路由模块
            },
            debug: function (){
                let {debug} = qs.parse(window.location.href.split("#")[0].split("?")[1])
                if(debug){
                    localStorage.clear()
                    sessionStorage.clear()
                }
            },
            afterLoadSubscribe: function(){
                if(this.subscribe == "false"){
                    Dialog({
                        showConfirmButton: false,
                        message: '请关注亚太天能公众号，系统操作消息将通过公众号及时通知到您'
                    });
                }else{
                    //若userId存在且有效
                    this.afterLoadUserId()
                }
            },
            afterLoadUserId: function (){
                //若还没重定向，则不需要进行以下操作
                if(this.userId){
                    TenonWebsocket.init("ws://app.aptenon.com"+basePrefix+"Ws/ws?userId=" + this.userId)

                    //对分享用户做路由跳转
                    let {devId,shareId,type,generateSharePassword} = qs.parse(window.location.href.split("#")[0].split("?")[1])
                    if(type == 'share'){
                        this.onGeneralClick('/'+type,{
                            devId: devId,
                            shareId: shareId
                        })
                    }else if(type == 'generateSharePassword'){
                        this.onGeneralClick('/'+type,{
                            devId: devId,
                            generateSharePassword: generateSharePassword
                        })
                    }
                }
            }
        }
    }
</script>

<style>
    #app {
        font-family: 'Avenir', Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
    }
</style>
